import 'package:amap_flutter_base/amap_flutter_base.dart';
import 'package:amap_flutter_map/amap_flutter_map.dart';
import 'package:flutter/material.dart';
import 'package:hxdj/common/components/my_tap_widget.dart';
import 'package:hxdj/common/components/my_text.dart';
import 'package:hxdj/common/my_header_global.dart';
import 'package:hxdj/home/address/edit_address/edit_address_viewmodel.dart';
import 'package:hxdj/home/address/loca_address/loca_address_viewmodel.dart';
import 'package:hxdj/home/locationManager/location_manager.dart';
import 'package:amap_flutter_search/amap_flutter_search.dart';
import 'package:provider/provider.dart';

class LocaAddressPage extends StatefulWidget {
  static String routeName = "/LocaAddressPage";

  const LocaAddressPage({super.key});

  @override
  State<LocaAddressPage> createState() => _LocaAddressPageState();
}

class _LocaAddressPageState extends State<LocaAddressPage> {
  late AMapController mapController;

  late LocaAddressViewModel viewModel;

  late final TextEditingController _searchController = TextEditingController();

  //焦点
  late FocusNode focusNode = FocusNode();

  //用户档当前的位置
  late CameraPosition cameraPosition;

  @override
  void initState() {
    super.initState();

    double latitude = double.parse(LocationManager.result!["latitude"].toString());
    double longitude = double.parse(LocationManager.result!["longitude"].toString());

    cameraPosition = CameraPosition(target: LatLng(latitude, longitude), zoom: 15.0);
    focusNode.addListener(() {
      //如果是第一焦点, 就要展示一个灰屏
      // if (focusNode.hasFocus) {
      //
      setState(() {});
    });
  }
  //搜索框
  _buildSearch() {
    String? city = LocationManager.result!["city"] as String?;

    return 
        Expanded(
      flex: 54,
      child: Container(
        margin: EdgeInsets.symmetric(horizontal: 15.w, vertical: 10.h),
        child: MyBorder(
          radius: 27.w,
          child: Container(
            child: Row(
              children: [
                Expanded(
                  flex: 102,
                  child: Container(
                    decoration: const BoxDecoration(
                        border: Border(
                      right: BorderSide(color: MyColours.colorD3D3D3, width: 1),
                    )),
                    child: MyTapWidget(
                      onTap: () {
                        //跳转到选择城市
                        // Navigator.pushNamed(context, "/CitySelectPage");
                      },
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [


                          MyText(city ?? "", fontSize: 12.sp, color: MyColours.text),
                          const Padding(
                            padding: EdgeInsets.only(left: 5.5),
                            child: MyImage(
                              imageName: "ic_arrow_right_reversal",
                              width: 9,
                              height: 5,
                            ),
                          )
                        ],
                      ),
                    ),
                  ),
                ),
                Expanded(
                    flex: 250,
                    child: Container(
                        child: Row(
                      children: [
                        const Padding(
                          padding: EdgeInsets.only(left: 15.5, right: 5.5),
                          child: MyImage(
                            imageName: "ic_search_address",
                            width: 11,
                            height: 11,
                          ),
                        ),
                        Expanded(
                          child: TextField(
                              controller: _searchController,
                              focusNode: focusNode,
                              onChanged: (value) {
                                //每次输入都搜索一下呢
                                viewModel.searchLocation(value);
                              },
                              onSubmitted: (value) {
                                // viewModel.searchLocation("");
                              },
                              decoration: InputDecoration(
                                hintText: '小区/酒店/标志物等',
                                hintStyle: TextStyle(color: MyColours.textGrayA, fontSize: 12.sp),
                                border: InputBorder.none, // 隐藏下划线
                                contentPadding: const EdgeInsets.fromLTRB(0, 5, 10.0, 12.0), // 内容内边距
                              )),
                        ),
                      ],
                    )))
              ],
            ),
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    //地图的初始化
    final AMapWidget map = AMapWidget(initialCameraPosition: cameraPosition);

    return BasePage<LocaAddressViewModel>(
        onModelReady: (model) {
          // 页面初始化完成后的回调
          viewModel = model;

          viewModel.defaultSearch();
        },
        viewModel: LocaAddressViewModel(),
        builder: (BuildContext context, LocaAddressViewModel? model, Widget? child) {
          return Scaffold(
            resizeToAvoidBottomInset: false,
            appBar: const MyAppBar(title: "选择地址"),
            backgroundColor: MyColours.bgColor,
            body: MyTapWidget(
              onTap: () {
                FocusManager.instance.primaryFocus!.unfocus();
              },
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  _buildSearch(),
                  Expanded(
                    flex: 550,
                    child: Stack(
                      children: [
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            ConstrainedBox(
                              constraints: BoxConstraints.expand(height: 185.h),
                              child: Stack(
                                alignment: Alignment.center,
                                children: [
                                  Container(
                                    child: map,
                                  ),
                                ],
                              ),
                            ),
                            Padding(
                              padding: EdgeInsets.only(left: 15.w, top: 15.h, bottom: 15.h),
                              child: const MyText("附近地址"),
                            ),
                            Expanded(
                                child: ListView.builder(
                                    padding: EdgeInsets.zero,
                                    itemCount: viewModel.defaultDataList.length,
                                    itemBuilder: (context, index) {
                                      AMapPoiModel poi = viewModel.defaultDataList[index];
                                      return SearchAddressItem(poiModel: poi);
                                    })),
                          ],
                        ),
                        focusNode.hasFocus
                            ? Positioned.fill(
                                child: Container(
                                    color: MyColours.bgColor.withOpacity(0.8),
                                    child: ListView.builder(
                                      itemCount: viewModel.dataList.length,
                                      itemBuilder: (context, index) {
                                        AMapPoiModel poi = viewModel.dataList[index];
                                        return SearchAddressItem(poiModel: poi);
                                      },
                                    )))
                            : Container(),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          );
        });
  }
}

class SearchAddressItem extends StatelessWidget {
  final AMapPoiModel poiModel;

  const SearchAddressItem({super.key, required this.poiModel});

  @override
  Widget build(BuildContext context) {
    return MyTapWidget(
      onTap: () {
        FocusManager.instance.primaryFocus!.unfocus();
        //选中后, 可以返回了
        Navigator.pop(context);

        EditAddressViewModel editAddressViewModel = Provider.of<EditAddressViewModel>(context, listen: false);
        editAddressViewModel.selectAddress(poiModel);
      },
      child: Container(
        color: MyColours.materialBg,
        padding: EdgeInsets.only(left: 15.w, right: 15.w, top: 15.h),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Padding(
              padding: EdgeInsets.only(top: 5.h, right: 6.5.w),
              child: const MyImage(
                imageName: "ic_distance",
                width: 10,
                height: 12,
              ),
            ),
            Expanded(
              child: Container(
                decoration: const BoxDecoration(
                    border: Border(
                  bottom: BorderSide(color: MyColours.colorD3D3D3, width: 1),
                )),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Padding(
                      padding: EdgeInsets.only(bottom: 10.h),
                      child: Text(poiModel.address ?? "", style: TextStyle(fontSize: 16.sp, color: MyColours.text)),
                    ),
                    Padding(
                      padding: EdgeInsets.only(bottom: 8.h),
                      child: Text(poiModel.name ?? "", style: TextStyle(fontSize: 12.sp, color: MyColours.textGrayA)),
                    ),
                  ],
                ),
              ),
            ),
            // Container(child: MyText("1000M", fontSize: 12.sp, color: MyColours.color8E6447)),
          ],
        ),
      ),
    );
  }
}
